package cn.itcast.controller;


import cn.itcast.Permission;
import cn.itcast.Role;
import cn.itcast.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 查询所有角色
     * @return
     * @throws Exception
     */
    @RequestMapping("/findAll")
    public ModelAndView findAll() throws Exception {
        ModelAndView mv = new ModelAndView();
        List<Role> roles = roleService.findAll();
        mv.addObject("roleList",roles);
        mv.setViewName("role-list");

        return mv;
    }

    /**
     * 根据id查询角色
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public ModelAndView findById(String id) throws Exception{
        Role role = roleService.findById(id);
        ModelAndView mv = new ModelAndView();
        mv.addObject("role",role);
        mv.setViewName("role-show");
        return mv;
    }


    /**
     * 添加角色
     * @param role
     * @return
     */
    @RequestMapping("/save")
    public String save (Role role) throws Exception{
        roleService.save(role);
        return "redirect:findAll";
    }

    /**
     * 根据roleId查询role以及可以添加的权限
     * @param roleId
     * @return
     * @throws Exception
     */
    @RequestMapping("/findRoleByIdAndAllpermission")
    public ModelAndView findRoleByIdAndAllpermission(@RequestParam(name = "id") String roleId) throws Exception{
        ModelAndView mv = new ModelAndView();

        Role role = roleService.findById(roleId);
        mv.addObject("role",role);

        List<Permission> otherPermission =  roleService.findOtherPermission(roleId);
        mv.addObject("permissionList",otherPermission);
        mv.setViewName("role-permission-add");
        return mv;
    }

    /**
     * 给角色添加权限
     * @return
     * @throws Exception
     */
    @RequestMapping("/addPermissionToRole")
    public String addPermissionToRole(@RequestParam(name = "roleId") String roleId,@RequestParam(name = "ids") String[] permissionIds)throws Exception{

        roleService.addPermissionToRole(roleId,permissionIds);
        return "redirect:findAll";
    }
}
